//
//  KVPlayer.m
//
//  Created by zhoubaitong on 2017/8/30.
//  Copyright © 2017年 cckv. All rights reserved.
//

#import "KVPlayer.h"

#import <AVFoundation/AVFoundation.h>

@interface KVPlayer()<AVAudioPlayerDelegate>

@property (nonatomic, strong) AVAudioPlayer *avAudioPlayer; // 播放器palyer
@property (nonatomic, copy) NSString *playName; // 播放器palyer
@property (nonatomic, copy) NSString *playType; // 播放器palyer

@end

@implementation KVPlayer

static KVPlayer *shareTool = nil;

/** 单例 */
+(instancetype)shareTool
{
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        
        shareTool = [[self alloc]init];
    });
    
    return shareTool;
}
-(AVAudioPlayer *)avAudioPlayer
{
    if (!_avAudioPlayer) {
        // 2.播放本地音频文件
        // (1)从boudle路径下读取音频文件 陈小春 - 独家记忆文件名，mp3文件格式
        NSString *path = [[NSBundle mainBundle] pathForResource:@"战前背景" ofType:@"mp3"];
        // (2)把音频文件转化成url格式
        NSURL *url = [NSURL fileURLWithPath:path];
        // (3)初始化音频类 并且添加播放文件
        _avAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
        // (4) 设置代理
        _avAudioPlayer.delegate = self;
        // (5) 设置初始音量大小 默认1，取值范围 0~1
        _avAudioPlayer.volume = 1;
        // (6)设置音乐播放次数 负数为一直循环，直到stop，0为一次，1为2次，以此类推
        _avAudioPlayer.numberOfLoops = -1;
        // (7)准备播放
        [_avAudioPlayer prepareToPlay];

    }
    return _avAudioPlayer;
}
- (void)paly
{
    [self.avAudioPlayer play];
}
- (void)palyWithName:(NSString*)name andType:(NSString*)type
{
    NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:type];
    // (2)把音频文件转化成url格式
    NSURL *url = [NSURL fileURLWithPath:path];

    // (3)初始化音频类 并且添加播放文件
    [KVPlayer shareTool].avAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];

    _avAudioPlayer.numberOfLoops = -1;
    // (7)准备播放
    [_avAudioPlayer prepareToPlay];
    
    [self.avAudioPlayer play];
}
- (void)stop
{
    [self.avAudioPlayer stop];
}

- (BOOL)isPlay
{
    return self.avAudioPlayer.isPlaying;

}

- (void)playAudio:(NSString*)name withType:(NSString*)type
{
    NSString *audioFile=[[NSBundle mainBundle] pathForResource:name ofType:type];
    NSURL *fileUrl=[NSURL fileURLWithPath:audioFile];
    //1.获得系统声音ID
    SystemSoundID soundID=0;
    /**
     * inFileUrl:音频文件url
     * outSystemSoundID:声音id（此函数会将音效文件加入到系统音频服务中并返回一个长整形ID）
     */
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)(fileUrl), &soundID);
    //如果需要在播放完之后执行某些操作，可以调用如下方法注册一个播放完成回调函数
    //2.播放音频
    AudioServicesPlaySystemSound(soundID);//播放音效
//    AudioServicesPlayAlertSound(soundID);//播放音效并震动
    
}
@end
